<?php
  /* File:    array2xml.php: provides xml2array() which can convert a parsed
   *          structure back to text XML
   * Type:    CMS function library
   * Author:  udo.schroeter@gmail.com
   * License: commercially licensed as part of the CMS package
   * Todo:    /
   * Changes: -
   */

  function _array2xml_getattributes(&$element)
  {
    $result = array();
    if (sizeof($element)>0)
      foreach ($element as $tk => $tv)
      {
        $result[] = $tk.'="'.addslashes($tv).'"';
      }
    return implode(' ',$result);
  }

  function _array2xml_getvalues(&$element)
  {
    return $element;
  }

  function _array2xml_is_mainelement($name)
  {
    return (strval(intval($name)) != strval($name));
  }

  function _recurse_array2xml(&$arraypart, $level, $parentname)
  {
    //Marco, 09.06.2004 | Added is_array check before foreach()
    //
    $result = '';
    $level = '';
    if (is_array($arraypart))
    {
      foreach ($arraypart as $k => $element)
      {
        if (is_array($element))
        {
          if (_array2xml_is_mainelement($k))
          {
            $tagname = $k;
            $result .= _recurse_array2xml($element, $level.'  ', $k);
          }
          else
          {
            $tagname = $parentname;
            $tagstart = $level."<".$tagname;
    
            $attributes = _array2xml_getattributes($element['@']);
            if ($attributes!='')
              $tagstart .= ' '.$attributes;
    
            $value = _array2xml_getvalues($element['$']);
    
            $desc = _recurse_array2xml($element, $level.'  ', $k);
    
            if ($desc!='')
            {
              $result .= $tagstart.">";
              $result .= ($desc);
              if ($value!='')
                $result .= $level.utf8_encode($value);
              $result .= $level."</".$tagname.">";
            }
            else
            {
              if ($value!='')
                $result .= $tagstart.">".utf8_encode($value)."</".$tagname.">";
              else
                $result .= $tagstart."/>";
            }
          }
        }
      }
    }
    return $result;
  }

  function array2xml(&$array)
  {
    $result = '';
    $narray = $array;
    if (!isset($array))
      return '';
    else
      return _recurse_array2xml($narray, '', 'root');
  }
   

?>
